package sky.cin.framework.extension.log;

import sky.cin.framework.sfoc.core.annotations.beans.Autowired;
import sky.cin.framework.sfoc.core.annotations.beans.Component;
import sky.cin.framework.sfoc.core.common.Context;
import sky.cin.framework.sfoc.core.common.utils.BeanUtils;
import sky.cin.framework.sfoc.core.interfaces.BeanPostProcessor;

import java.lang.reflect.Field;
import java.util.Map;

@Component
public class LoggerPostProcessor implements BeanPostProcessor {
    
    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) {
        if (bean == null) {
            return bean;
        }
        Field[] fields = bean.getClass().getDeclaredFields();
        for (Field field : fields) {
            if (BeanUtils.isAnnotationPresent(field, Autowired.class) && field.getType() == Croog.class) {
                try {
                    field.setAccessible(true);
                    Croog logger = (Croog) field.get(bean);
                    logger.setPackage(bean.getClass().getTypeName());
                    Map<Object, Object> config = Context.getApplicationConfig().getMap("log");
                    if (config != null) {
                        config.forEach((k, v) -> {
                            Croog.putLimit(k.toString(), v.toString());
                        });
                    }
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        }
        return bean;
    }
}
